package red.internal.client.registry;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import red.client.registry.Host;
import red.client.registry.RegistryInstance;
import red.internal.core.message.RegistryCommand;
import red.internal.core.message.RegistryItem;
import red.internal.core.message.RegistryMessage;

import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * @author Jin Zheng
 * @since 2020-07-12
 */
public class DefaultRegistryInstance implements RegistryInstance
{
	private static Logger logger = LoggerFactory.getLogger(DefaultRegistryInstance.class);

	private final Set<String> nameSet = new HashSet<>();
	private final Set<Host> hostSet = new HashSet<>();

	public DefaultRegistryInstance()
	{
	}

	public static RegistryInstance from(RegistryMessage message)
	{
		RegistryInstance instance = new DefaultRegistryInstance();
		instance.addNames(message.getNameSet());
		for (RegistryItem item : message.getItemSet())
		{
			DefaultHost host = new DefaultHost(item.getItem());
			host.setToken(item.getToken());
			instance.addHost(host);
		}
		return instance;
	}

	public static RegistryMessage toMessage(RegistryInstance instance, RegistryCommand command)
	{
		RegistryMessage message = RegistryMessage.create(command);
		message.addNameList(instance.getNameList());
		for (Host host : instance.getHostList())
		{
			DefaultHost hostImpl = (DefaultHost)host;
			RegistryItem item = new RegistryItem(hostImpl.toString(), hostImpl.getToken());
			message.addItem(item);
		}
		return message;
	}

	@Override
	public void addName(String name)
	{
		if (name == null || name.isEmpty())
			return;

		nameSet.add(name);
	}

	@Override
	public void addNames(Collection<String> names)
	{
		if (names == null || names.isEmpty())
			return;

		nameSet.addAll(names);
	}

	@Override
	public void addHost(Host host)
	{
		if (host == null)
			return;

		hostSet.add(host);
	}

	@Override
	public void addHosts(Collection<Host> hosts)
	{
		if (hosts == null || hosts.isEmpty())
			return;

		hostSet.addAll(hosts);
	}

	@Override
	public String getName()
	{
		if (nameSet.isEmpty())
			return null;

		return nameSet.iterator().next();
	}

	@Override
	public List<String> getNameList()
	{
		return List.copyOf(nameSet);
	}

	@Override
	public Host getHost()
	{
		if (hostSet.isEmpty())
			return null;

		return hostSet.iterator().next();
	}

	@Override
	public List<Host> getHostList()
	{
		return List.copyOf(hostSet);
	}
}
